import MathUtils from "../utils/MathUtils";
import Common from "../utils/Common";
import { CustomAdGroup } from "./CustomAdGroup";
import { NativeGroup } from "./NativeGroup";
import { platformUtil } from "./platformUtil";
import { appConfig } from "../model/appConfig";
import { BannerOptions } from "./BannerOptions";
import { MSG, SHARE_CHANNEL, VIDEO_STATUS } from "../const/MSG";
import { httpUtil } from "../framework/modules/httpUtil";
import dataUtil from "../framework/modules/dataUtil";
import eventUtil from "../framework/modules/eventUtil";
import { CustomOptions } from "./CustomOptions";
import { BlockOptions } from "./BlockOptions";
import { NativeSize } from "./NativeSize";
import nativeAdResult from "../model/nativeAdResult";
import NativeOptions from "./NativeOptions";
import { EventConst } from "../const/Const";
import { platformConf } from "./platformConf";
import { IPlatform } from "./IPlatform";
import { shareInfo } from "../model/shareInfo";
import { AdVertical } from "./AdVertical";
import { AdHorizontal } from "./AdHorizontal";
import { View } from "cc";
import { memoryConfig } from "../framework/modules/memoryConfig";
import { Debug } from "../utils/Debug";
import ADController from "../../3rd/Guyu/Scripts/[业务]/广告任务/Controller/广告/ADController";



// var videoLoading: boolean = false;
// var videoCb = null;
export default class PlatformModule implements IPlatform {

    constructor() {

        // this._regisiterWXCallback();
        // this.initShare(true);
        this.share_clickTime = null!; //分享拉起时间
        this.currentShareCallback = () => { }; //模拟分享回调
        this.currentShortCall = () => { }; //模拟分享回调
        this.shareFail = false;

        this.updateProgram();
        this.initRecord();


    }

    public baseUrl = "https://api.liteplay.com.cn/";
    public idConfig: appConfig = null!;
    public share_clickTime: number = -1;
    public currentShareCallback: (success: boolean) => void;
    public currentShortCall: (success: boolean) => void;
    public shareFail: boolean = false;
    public vibrateOn: boolean = false;
    public systemInfo: any = null;

    public bannerOption: BannerOptions = null!;
    public block: any = null;
    public currentBannerId: string = "";
    public currentVideoId: string = "";
    public mVideo: any = null;
    public inter: any = null;
    public native: any = null;
    public nativePic: any = null;
    public nativeLR: any = null;
    public customAd: any = [];
    public box: any = null;

    public platformName: string = "wx";


    public bannerErrorQuene = [];




    public nativeIdIndex: number = 0;


    public bannerShowCount: number = 0;
    public bannerShowCountLimit: number = 3;

    public bannerShowTime: number = 0;
    public bannerShowTimeLimit: number = 15;
    public bannerLimitType: number = 0;

    public bannerCb: (isOpend: boolean) => void = null!;
    public isBannerShow: boolean = false;

    public blockWidth: number = 300;
    public blockHeigth: number = 96;

    public videoCb: (res: any) => void = null!;
    public videoLoading: boolean = false;
    public videoPlaying: boolean = false;
    public interShowCount: number = 0;
    public interShowCountLimit: number = 3;


    public nativeAdResult: nativeAdResult = null!;
    public nativeAdResultList: Array<nativeAdResult> = [];
    ;
    public isInterLoaded: boolean = false;

    public nativeCb: Function = null!;
    public nativeLoading: boolean = false;

    public recordObj: any = null;


    public shareInfoArr: Array<shareInfo> = [];

    public GetRandomId(idArray: Array<string> | string, index: number = 0) {
        if (idArray instanceof Array) {
            if (idArray.length > 0) {
                if (index < 0) {
                    return idArray[Common.randomNumBoth(0, idArray.length - 1)];
                }
                else if (idArray.length - 1 < index) {
                    Debug.warn(`id数组小于传入索引值，本次使用${idArray[0]}，请检查代码`, idArray, index)
                    return idArray[0]
                }
                return idArray[index]
            }
            else {
                Debug.warn('Id 配置为空')
                return null;
            }
        }
        else {
            return idArray;
        }
    }

    public GetRandomCustomGroup(ids: Array<CustomAdGroup>, index: number = -1): CustomAdGroup {
        if (ids.length > 0) {
            if (index == -1)
                return ids[Common.randomNumBoth(0, ids.length - 1)];
            else {
                if (index < ids.length) {
                    return ids[index];
                }
            }
        }
        return ids[0];
    }
    public GetRandomNativeGroup(ids: Array<NativeGroup>, size: NativeSize, index: number = -1) {
        if (ids.length > 0) {
            if (index == -1) {
                var temp = ids.filter(item => item.Size == size);
                return temp[Common.randomNumBoth(0, temp.length - 1)];
            }
            else {
                if (index < ids.length) {
                    if (ids[index].Size == size)
                        return ids[index];
                    else
                        return ids.find(item => item.Size == size);
                }
                else {
                    return ids.find(item => item.Size == size);
                }
            }
        }
        Debug.log("原生广告ID选取失败，选取第一个");
        return ids[0];
    }



    public getBannerId(idx: number = 0) {
        return this.GetRandomId(platformConf.config.bannerIdList, idx)
    };

    public getBlockId(idx: number = 0) {
        return this.GetRandomId(platformConf.config.blockIdList, idx)
    };

    public getVideoId(idx: number = 0) {
        return this.GetRandomId(platformConf.config.videoIdList, idx)
    };
    public getCustomId(idx: number = 0) {
        return this.GetRandomCustomGroup(platformConf.config.customIdList, idx)
    };
    public get interId() {
        return this.GetRandomId(platformConf.config.interIdList, -1)
    };
    public get boxId() {
        return this.GetRandomId(platformConf.config.BoxPortalIdList, -1)
    };

    public get gameBannerId() {
        return this.GetRandomId(platformConf.config.gameBannerIdList, -1)
    };

    public get gamePortalId() {
        return this.GetRandomId(platformConf.config.gamePortalIdList, -1)
    };
    public get nativeLRId() {
        return this.GetRandomNativeGroup(platformConf.config.nativeList, NativeSize.LR, -1);
    }
    public get nativePicId() {
        return this.GetRandomNativeGroup(platformConf.config.nativeList, NativeSize.PIC, -1);
    }

    public checkWindow(): boolean {
        var g = window as any;
        if (!g[this.platformName]) return false;
        return true;
    }
    public checkMethod(methodName: string): boolean {
        var g = window as any;
        if (!g[this.platformName]) return false;
        if (!g[this.platformName][methodName]) {
            Debug.log(`checkMethod ${methodName} 失败`);
            return false
        };
        return true;
    }

    public getWindow(): any {
        var g = window as any;
        return g;
        if (!g[this.platformName]) return null;
        return g[this.platformName];
    }

    onEnable() {


    }
    private vibrateSwitch(on: boolean) {
        this.vibrateOn = on;
    }

    /***
     * 检测IphoneX
     */
    public isIphoneXModel() {
        var g = window as any;
        if (!g[this.platformName]) return;
        let sysInfo = this.getSystemInfoSync();
        if (/iphone x/.test(sysInfo.model.toLowerCase())) {
            return true;
        } else {
            return false;
        }
    }
    /***
     * 检测Iphone
     */
    public isIphone() {
        var g = window as any;
        if (!g[this.platformName]) return;
        let sysInfo = this.getSystemInfoSync();
        if (/iphone/.test(sysInfo.model.toLowerCase())) {
            return true;
        } else {
            return false;
        }
    }

    public isIphoneX() {
        var g = window as any;
        if (!g[this.platformName]) return;
        let sysInfo = this.getSystemInfoSync();
        let screenHeight = sysInfo.screenHeight;
        let screenWidth = sysInfo.screenWidth;
        let ratioWH = screenWidth / screenHeight;
        if (ratioWH <= 0.5 || ratioWH >= 2) {
            return true;
        } else {
            return false;
        }
        // let lanscape = screenHeight == 375 && screenWidth == 812;
        // let portrait = screenHeight == 812 && screenWidth == 375;
        // if (lanscape || portrait) {
        //     return true;
        // }
        // return false;
    }

    private compareVersion(v1: string, v2: string) {
        let v11 = v1.split('.')
        let v22 = v2.split('.')
        const len = Math.max(v11.length, v22.length)

        while (v1.length < len) {
            v11.push('0')
        }
        while (v2.length < len) {
            v22.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    }
    /**
    * 检测版本是否可用
    * @param version 需要检查的版本号
    */
    public supportVersion(version: string) {
        let sdkVersion = this.getSystemInfoSync().SDKVersion
        return (this.compareVersion(sdkVersion, version) >= 0);
    }

    /**
     * 是否支持函数
     * @param name 
     */
    public supportFunction(name: string) {
        var g = window as any;
        if (!g[this.platformName]) return false;
        if (!g[this.platformName][name]) return false;
        return true;
    }

    private versionRet: boolean = null!;
    /**
     * 检查当前版本的导出广告是否开启
     * @param {string} version 版本号 为了兼容旧版本SDK的参数，目前已无作用，SDK会取moosnowConfig 中的version 来判断
     * @param {*} callback 
     * @returns callback回调函数的参数为boolean，true：打开广告，false：关闭广告
     */
    public checkVersion(version: string, callback: Function) {
        if (this.versionRet != null) {
            callback(this.versionRet);
            return;
        } else {
            this._checkConfigVersion(callback)
        }
    }
    private _checkRemoteVersion(callback: Function) {
        var url = this.baseUrl + 'admin/wx_list/getAppConfig';
        var signParams = {
            appid: platformConf.config.appId,
        };
        let data = signParams;
        httpUtil.request(url, data, 'POST',
            (res: any) => {
                this.versionRet = this.checkLog(res.data.version)
                callback(this.versionRet);

            },
            () => {
                Debug.log('checkVersion fail');
            },
            () => {
                Debug.log('checkVersion complete');
            }
        );
    }
    private _checkConfigVersion(callback: Function) {
        httpUtil.getAllConfig((res: any) => {
            if (res && res.version) {
                this.versionRet = this.checkLog(res.version);
                callback(this.versionRet)
            }
            else {
                this._checkRemoteVersion(callback);
            }
        })
    }

    public checkLog(remoteVersion: string) {
        let configVersion = platformConf.config.version
        let versionRet = remoteVersion != configVersion;
        Debug.log(`版本检查 后台版本${remoteVersion} 配置文件版本${configVersion}`)
        Debug.log("获取广告开关：", versionRet);
        return versionRet;
    }


    public isSmallWidth() {
        var g = window as any;
        if (!g[this.platformName]) return;
        let sysInfo = this.getSystemInfoSync();
        let screenHeight = sysInfo.screenHeight;
        let screenWidth = sysInfo.screenWidth;
        if (screenHeight < 667) {
            Debug.log('高度不够', screenHeight);
            return true;
        }
        return false;
    }

    public login(success?: (t: string) => void, fail?: Function) {
        let token = dataUtil.getToken()
        if (token == "") {
            token = Common.generateUUID();
            token = token.replace(/-/g, '')
            dataUtil.setToken(token);
        }
        if (Common.isFunction(success)) {
            if (success)
                success(token);
        }
    }

    // public login(callback?: Function, fail?: Function) {
    //     var self = this;
    //     window[this.platformName].login({
    //         success: (res) => {
    //             if (res.code) {
    //                 //发起网络请求
    //                 self.getUserToken(res.code, "", callback)
    //             } else {
    //                 if (Common.isFunction(callback))
    //                     callback({})
    //             }
    //         },
    //         fail: (res) => {
    //             if (Common.isFunction(callback))
    //                 callback({})
    //         }
    //     })
    // }


    public postMessage(data: { action: number, data?: any }) {
        var g = window as any;
        if (!g[this.platformName]) return;
        // Debug.log("postMessage:", data);
        if (!g[this.platformName].getOpenDataContext) return;
        g[this.platformName].getOpenDataContext().postMessage(data);
    }

    public navigate2Video(videoid: string) {

    }

    public getClipboardData(success: (res: string) => void, fail: (res: string) => void) {
        var g = window as any;
        if (!g[this.platformName]) return;
        if (!g[this.platformName].getClipboardData) return;
        g[this.platformName].getClipboardData({
            success: (res: any) => {
                if (success)
                    success(res.data)
                Debug.log(`${res.data}`);
            },
            fail: (res: any) => {
                if (fail)
                    fail(res)
                Debug.log(`getClipboardData调用失败`);
            },
        });
    }

    public setClipboardData(msg: string, success: (res: any) => void, fail: (res: any) => void) {
        var g = window as any;
        if (!g[this.platformName]) return;
        if (!g[this.platformName].setClipboardData) return;
        g[this.platformName].setClipboardData({
            data: msg,
            success: (res: any) => {
                if (success)
                    success(res)
                Debug.log(`setClipboardData调用成功`);
            },
            fail: (res: any) => {
                if (fail)
                    fail(res)
                Debug.log(`setClipboardData调用失败`);
            },
        });

    }

    /**
     * 更新版本
     */
    private updateProgram() {
        var g = window as any;
        let self = this;
        if (!g[this.platformName]) return;
        if (typeof g[this.platformName].getUpdateManager === 'function') { // 请在使用前先判断是否支持
            const updateManager = g[this.platformName].getUpdateManager()
            updateManager.onCheckForUpdate(function (res: any) {
                // 请求完新版本信息的回调
                // Debug.log('是否有新版本', res.hasUpdate);
            })

            updateManager.onUpdateReady(function (res: any) {
                self.showModal('游戏有新内容啦', '新的内容更精彩，来体验一下吧', '放弃', '体验', function (res) {
                    if (res)
                        updateManager.applyUpdate();
                });
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            })

            updateManager.onUpdateFailed(function () {
                // 新的版本下载失败
            })
        }
    }



    /**
     * 短震动
     */
    public vibrateShort() {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (win[this.platformName] && !win[this.platformName].vibrateShort) return;
        win[this.platformName].vibrateShort();
    }
    /**
     * 长震动
     */
    public vibrateLong() {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (win[this.platformName] && !win[this.platformName].vibrateLong) return;
        win[this.platformName].vibrateLong();
    }
    public showLoading(title: string) {
        if (!this.checkMethod("showLoading")) {
            Debug.log('showLoading', title)
            return;
        }
        var win = this.getWindow();
        win[this.platformName].showLoading({
            title: title,
            mask: false,
            success: null,
            fail: null,
            complete: null
        });
    }
    public hideLoading() {
        if (!this.checkMethod("hideLoading")) {
            return;
        }
        var win = this.getWindow();
        win[this.platformName].hideLoading();
    }
    public showModal(title: string, content: string, cancelTitle: string, confirmTitle: string, confirm: (res: any) => void) {
        if (!this.checkMethod("showModal")) {
            return;
        }
        var win = this.getWindow();
        win[this.platformName].showModal({
            title: title,
            content: content,
            cancelText: cancelTitle,
            confirmText: confirmTitle,
            showCancel: true,
            cancelColor: '#000000',
            confirmColor: '#3CC51F',
            fail: null,
            complete: null,
            success: (res: any) => {
                if (res.confirm) {
                    if (confirm) confirm(true);
                    // Debug.log('用户点击确定')
                } else if (res.cancel) {
                    if (confirm) confirm(false);
                    // Debug.log('用户点击取消')
                }
            }
        })
    }

    public showModalWithoutCancel(title: string, content: string, confirmTitle: string, confirm: (res: any) => void) {
        if (!this.checkMethod("showModal")) {
            return;
        }
        var win = this.getWindow();
        win[this.platformName].showModal({
            title: title,
            content: content,
            showCancel: false,
            confirmText: confirmTitle,
            cancelColor: '#000000',
            confirmColor: '#3CC51F',
            cancelText: '',
            fail: null,
            complete: null,
            success: (res: any) => {
                if (res.confirm) {
                    if (confirm) confirm(true);
                    // Debug.log('用户点击确定')
                } else if (res.cancel) {
                    if (confirm) confirm(false);
                    // Debug.log('用户点击取消')
                }
            }
        })
    }

    public showToast(title: string, toastType: string = 'none', mask: boolean = false) {
        if (!this.checkMethod("showToast")) {
            return;
        }
        var win = this.getWindow();
        win[this.platformName].showToast({
            title: title,
            icon: toastType,
            duration: 2000,
            mask: mask,
            image: null,
            success: null,
            fail: null,
            complete: null
        })
    }

    public authOrGetUserInfo(callback: (userInfo: any, flag: boolean) => void) {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        let self = this;

        this.getSetting(
            function (setting: any) {
                Debug.log('授权信息', setting);
                if (setting['scope.userInfo']) {
                    //已经授权
                    self.getUserInfo(
                        function (userInfo) {
                            //获取用户信息成功
                            Debug.log('获取用户信息：', userInfo);
                            callback(userInfo, false);
                        },
                        function (error: any) {
                            //获取用户信息失败
                            // callback(null);
                        });
                } else {
                    //未授权
                    self.showUserInfoButton(
                        function (userInfo) {
                            callback(userInfo, true);
                            Debug.log('授权获取用户信息：', userInfo);
                        }
                    );
                }
            },
            function (error: any) {
                //获取授权设置失败
                self.showUserInfoButton(
                    function (userInfo) {
                        callback(userInfo, true);
                        Debug.log('授权获取用户信息：', userInfo);
                    }
                );
            });



    }

    private showUserInfoButton(callback: (userInfo: any) => void) {
        let obj = {
            type: 'text',
            text: '',
            style: this._initLoginButton(),
        };
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        let btn = win[this.platformName].createUserInfoButton(obj);
        btn.onTap(function (res: any) {
            if (res.userInfo && res.userInfo.nickName) {
                //授权成功
                callback(res.userInfo);
                btn.hide();
            } else {
                //授权失败
                callback(null);
            }
        });
        btn.show();
    }

    private getSetting(success: Function, fail: Function) {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        win[this.platformName].getSetting({
            success: function (res: any) {
                success(res.authSetting);
                // res.authSetting = {
                //   "scope.userInfo": true,
                //   "scope.userLocation": true
                // }
            },
            fail: function () {
                fail();
            },
            complete: null,
        })
    }

    private getUserInfo(success: (userInfo: any) => void, fail: Function) {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        win[this.platformName].getUserInfo({
            success: function (res: any) {
                success(res.userInfo);
            },
            fail: function () {
                fail();
            },
            withCredentials: false,
            complete: null,
            lang: 'en',
        })
    }
    private mLaunchOption: any = undefined
    /**
     * 获取游戏启动参数
     * 返回值
     * scene	number	场景值	
     * query	Object	启动参数	
     * isSticky	boolean	当前小游戏是否被显示在聊天顶部	
     * shareTicket	string	shareTicket   分享到群后点击进入小游戏会有此变量 
     */
    public getLaunchOption() {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (this.mLaunchOption == undefined) {
            if (win[this.platformName]) {
                if (win[this.platformName].getEnterOptionsSync)
                    this.mLaunchOption = win[this.platformName].getEnterOptionsSync();
                if (win[this.platformName].getLaunchOptionsSync)
                    this.mLaunchOption = win[this.platformName].getLaunchOptionsSync();
            }
            else {
                this.mLaunchOption = {}
            }
        }
        return this.mLaunchOption;
    }

    /**
     * return obj
     * brand	string	手机品牌
     * model	string	手机型号
     * pixelRatio	number	设备像素比
     * screenWidth	number	屏幕宽度
     * screenHeight	number	屏幕高度
     * windowWidth	number	可使用窗口宽度
     * windowHeight	number	可使用窗口高度
     * language	string	微信设置的语言
     * version	string	微信版本号
     * system	string	操作系统版本
     * platform	string	客户端平台
     * fontSizeSetting	number	用户字体大小设置。以“我-设置-通用-字体大小”中的设置为准，单位 px。	>= 1.5.0
     * SDKVersion	string	客户端基础库版本	                                >= 1.1.0
     * benchmarkLevel	number	性能等级，-2 或 0：该设备无法运行小游戏，-1：性能未知，>=1 设备性能值，该值越高，设备性能越好(目前设备最高不到50)	                                >= 1.8.0
     * battery	number	电量，范围 1 - 100	                                   >= 1.9.0
     * wifiSignal	number	wifi 信号强度，范围 0 - 4	                        >= 1.9.0
     */
    public getSystemInfoSync() {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (this.systemInfo == null) {
            if (win[this.platformName] && win[this.platformName].getSystemInfoSync)
                this.systemInfo = win[this.platformName].getSystemInfoSync();
            else
                this.systemInfo = {}
            Debug.log(MSG.SYSTEM_INFO, JSON.stringify(this.systemInfo))
        }
        return this.systemInfo;
    }
    /**
     * 横屏还是竖屏
     * @param windowHeight 
     * @param windowWidth 
     */
    public isLandscape(windowHeight: number, windowWidth: number) {
        return windowHeight < windowWidth
    }

    //-----------------分享------------------
    public initShare(shareInfoArr: Array<shareInfo>) {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName]) return;
        if (!win[this.platformName].showShareMenu) return;
        this.shareInfoArr = shareInfoArr;
        win[this.platformName].showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
            success: null,
            fail: null,
            complete: null
        });
        if (win[this.platformName].onShareAppMessage)
            win[this.platformName].onShareAppMessage(() => {
                return this.buildShareInfo();
            });
        if (win[this.platformName].onShareTimeline)
            // 绑定分享参数
            win[this.platformName].onShareTimeline(() => {
                return this.buildShareInfo();
            })
    }

    public getShareInfo(ticket: string, success: (encryptedData: string, iv: string) => void, fail?: Function) {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName]) {
            return;
        }
        win[this.platformName].getShareInfo({
            shareTicket: ticket,
            success: function (res: any) {
                success(res.encryptedData, res.iv);
            },
            fail: function () {
                if (fail) fail();
            },
            complete: null,
        });
    }
    /**
     * 分享
     * @param query 分享参数 { channel:moosnow.SHARE_CHANNEL.LINK }  
     * SHARE_CHANNEL.LINK, SHARE_CHANNEL.ARTICLE, SHARE_CHANNEL.TOKEN, SHARE_CHANNEL.VIDEO 可选 仅字节跳动有效
     * @param callback 分享成功回调参数 = true, 分享失败回调参数 = false,
     * @param shortCall 时间过短时回调 ,err 是具体错误信息，目前只在头条分享录屏时用到
     */
    public share(query: SHARE_CHANNEL, callback?: (shared: boolean) => void, shortCall?: (err: any) => void) {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName]) {
            if (callback)
                callback(true);
            return;
        }
        this.currentShareCallback = callback!;
        this.currentShortCall = shortCall!;
        this.share_clickTime = Date.now();
        this.shareFail = false;
        this._share(query);
    }

    public shareWithoutCheck(query: SHARE_CHANNEL, callback?: (shared: boolean) => void) {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName]) {
            if (callback)
                callback(true);
        }
        this.currentShareCallback = callback!;
        this.share_clickTime = 1;
        this.shareFail = false;
        this._share(query);
    }

    private _share(query: SHARE_CHANNEL = SHARE_CHANNEL.LINK) {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName]) {
            this.currentShareCallback(true)
            return
        };;
        if (!win[this.platformName].shareAppMessage) {
            this.currentShareCallback(true)
            return
        };
        let self = this;
        let shareInfo = this.buildShareInfo(query);
        Debug.log('分享数据：', shareInfo)
        win[this.platformName].shareAppMessage(shareInfo);
    }

    //构建分享内容
    public buildShareInfo(query: SHARE_CHANNEL = SHARE_CHANNEL.LINK) {
        let title = "", imageUrl = ""
        if (this.shareInfoArr.length > 0) {
            let item = this.shareInfoArr[MathUtils.randomNumBoth(0, this.shareInfoArr.length - 1)];
            title = item.title;
            imageUrl = item.img;
        }
        let shareInfo = {
            title: title,
            imageUrl: imageUrl,
            query: query,
        };
        return shareInfo;
    }

    private _onShareback() {
        let self = this;
        setTimeout(() => {
            if (this.share_clickTime && this.currentShareCallback) {
                // Debug.log('分享回来:',this.shareFail);
                if (this.shareFail) {
                    this.currentShareCallback(false);
                } else {
                    if (this.share_clickTime == 1 || (Date.now() - this.share_clickTime >= 3 * 1000)) {
                        //分享成功
                        this.currentShareCallback(true);
                        // Debug.log('分享成功',this.shareFail);
                    } else {
                        this.currentShareCallback(false);
                        // Debug.log('分享失败',this.shareFail);
                    }
                }
            }
            this.shareFail = false;
            this.currentShareCallback = null!;
            this.share_clickTime = null!;
        }, 100);
    }

    private _initLoginButton() {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName]) return;
        let wxsys = win[this.platformName].getSystemInfoSync();
        let style = {
            left: 0,
            top: 0,
            width: wxsys.screenWidth,
            height: wxsys.screenHeight,
            lineHeight: 40,
            // backgroundColor: '#de0000',
            color: '#ffffff',
            type: 'text',
            text: '获取用户信息',
            textAlign: 'center',
            fontSize: 28,
            // borderRadius: 5,
        }
        return style;
    }
    //-----------------录屏 具体逻辑在子类实现------------------
    public initRecord() { }
    /**
     * 裁剪视频
     * @param timeRange 默认[2,2] 裁剪视频时保留的前后时长
     * @param callback 剪切完成时回调
     */
    public clipRecord(timeRange: Array<number> = [2, 2], callback: (res: any) => void) { };
    /**
     * 开始录屏
     * @param duration 录屏时长
     * @param callback 如果不是抖音回调参数=false
     */
    public startRecord(duration = 300, callback: (douyin: boolean) => void) {
        if (!this.recordObj) {
            if (callback)
                callback(false);
            return;
        }
    }
    /**
     * 停止录屏
     * @param callback 如果不是抖音回调参数=false，如果录制成功，回调参数中录屏地址=res.videoPath
     */
    public stopRecord(callback: (douyin: boolean) => void) {
        if (!this.recordObj) {
            if (callback)
                callback(false);
            return;
        }
    }

    public pauseRecord() {
    }
    public resumeRecord() {
    }
    /**
     * 
     * @param style 
     * @param timeRange 
     * @param callback 
     */
    public showShareButton(style: object, timeRange?: Array<Array<number>>, callback?: Function) {

    }

    public hideShareButton() {

    }
    //-----------------注册事件------------------

    /**
     * 注册微信各种回调
     */
    public _regisiterWXCallback() {
        if (!this.checkWindow()) return;
        this._regisiterOnShow();
        this._regisiterOnHide();
    }

    private _regisiterOnShow() {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName].onShow) return;
        let self = this;
        win[this.platformName].onShow((res: any) => {
            self._onShowCallback(res);
        });
    }

    private _onShowCallback(res: any) {
        this._onShareback();
        Debug.log('on show ', res)
        eventUtil.sendEventImmediately(EventConst.ON_PLATFORM_SHOW, res);
    }

    private _regisiterOnHide() {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName].onHide) return;
        let self = this;
        win[this.platformName].onHide((res: any) => {
            self._onHideCallback(res)
        });
    }

    private _onHideCallback(res: any) {
        //Lite.log.log('WX_hide');
        Debug.log('on show ', res)
        eventUtil.sendEventImmediately(EventConst.ON_PLATFORM_HIDE, res);
        Debug.log('on hide ', res)
        let isOpend = res && ((res.targetAction == 8 || res.targetAction == 9 || res.targetAction == 10) && res.targetPagePath.length > 50)
        if (isOpend) {
            httpUtil.clickBanner();
        }
        if (this.bannerCb) {
            this.bannerCb(isOpend);
        }
        else {
            Debug.log('banner callback is null ')
        }
    }

    //-----------------Banner广告------------------
    public initBanner() {
        if (!this.checkWindow()) return;
        var win = this.getWindow();
        // this.prepareBanner()
    }
    public mBannerAd: any;
    private onBannerLoadCallback: Function = null!;
    public prepareBanner(option: BannerOptions, onComplete: () => void) {
        this.bannerOption = option;
        this.onBannerLoadCallback = onComplete;
        if (!this.checkMethod("createBannerAd")) return;
        var win = this.getWindow();
        let style = option.getBannerStyle(this.getSystemInfoSync());
        let bannerId = this.GetRandomId(platformConf.config.bannerIdList);

        Debug.log(`使用id[${bannerId}]创建banner`);
        this.mBannerAd = win[this.platformName].createBannerAd({
            adUnitId: bannerId,
            adIntervals: 30,
            style: style
        });
        this.mBannerAd.isLoaded = false;
        this.mBannerAd.bannerShowCount = 0;
        this.mBannerAd.bannerShowTime = Date.now();
        if (this.mBannerAd) {
            this.mBannerAd.onResize(this.onBannerResize.bind(this, bannerId));
            this.mBannerAd.onError(this.onBannerError.bind(this, bannerId));
            this.mBannerAd.onLoad(this.onBannerLoad.bind(this, bannerId));
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="option"></param>
    public showBanner(option: BannerOptions) {
        if (this.mBannerAd == null) {
            this.prepareBanner(option, () => {
                this.mBannerAd.show();
            });
        }
        else {
            this.mBannerAd.show();
        }
    }
    public hideBanner(destroy: boolean = false) {
        if (this.mBannerAd != null) {
            this.mBannerAd.hide();
            if (destroy) {
                this.mBannerAd.offLoad(null);
                this.mBannerAd.offResize(null);
                this.mBannerAd.offError(null);
                this.mBannerAd.destroy();
                this.mBannerAd = null;
            }
        }
    }

    public onBannerLoad(bannerId: string) {
        this.bannerShowCount = 0;
        if (this.onBannerLoadCallback)
            this.onBannerLoadCallback();
    }
    public onBannerError(bannerId: string, err: any) {
        Debug.warn('banner___error:', err);
    }
    public onBannerResize(bannerId: string, size: any) {
        Debug.log("onBannerResize -> size", size)
        let wxsys = this.getSystemInfoSync();
        let owner = this.mBannerAd
        if (this.mBannerAd) {
            if (owner.style) {
                if (!isNaN(owner.style.realWidth))
                    this.bannerOption.Width = owner.style.realWidth;
                if (!isNaN(owner.style.realHeight))
                    this.bannerOption.Height = owner.style.realHeight;
            }
            else {
                Debug.warn("onBannerResize -> owner 1", owner)
            }

        }
        if (owner && owner.style) {
            var style = this.bannerOption.getBannerStyle(wxsys);
            owner.style.left = style.left;
        }
        else {
            Debug.warn("onBannerResize -> owner 2", owner)
        }
    }



    public exitApplication() {

    }


    //------------广告video------------
    public initVideo() {
        this.createRewardAD(false);
    }
    public createRewardAD(show: boolean, idIndex: number = 0) {
        if (this.videoLoading) {
            return;
        }
        let videoId = this.getVideoId(idIndex);
        Debug.warn('视频id', videoId)
        var win = this.getWindow();
        if (!win[this.platformName]) {
            if (this.videoCb)
                this.videoCb(VIDEO_STATUS.END);
            return;
        }
        if (!win[this.platformName].createRewardedVideoAd) {
            if (this.videoCb)
                this.videoCb(VIDEO_STATUS.END);
            return;
        }

        if (Common.isEmpty(videoId)) {
            Debug.warn(MSG.VIDEO_KEY_IS_NULL)
            if (this.videoCb)
                this.videoCb(VIDEO_STATUS.END);
            return;
        }
        if (!this.mVideo) {
            this.mVideo = win[this.platformName].createRewardedVideoAd({
                adUnitId: videoId
            });
            if (!this.mVideo) {
                Debug.warn('创建视频广告失败')
                return;
            }
            this.mVideo.onError(this.onVideoError.bind(this));
            this.mVideo.onClose(this.onVideoClose.bind(this));
            this.mVideo.onLoad(this.onVideoLoad.bind(this));
        }
        this.videoLoading = true;
        this.videoPlaying = false;
        this.mVideo.load()
            .then(() => {
                if (show) {
                    this.videoPlaying = true;
                    this.mVideo.show()
                        .then(() => {
                            this.videoLoading = false;
                        })
                        .catch((err: any) => {
                            this.videoLoading = false;
                            this.onVideoError(err.errMsg, err.errCode);
                            Debug.log(err.errMsg);
                        });
                }
            }).catch((err: any) => {
                this.onVideoError(err.errMsg, err.errCode);
                Debug.log(err.errMsg);
            });
    }

    public onVideoError(msg: string, code: string) {
        Debug.log(MSG.VIDEO_ERROR_COMPLETED, msg, code)
        this.videoLoading = false;
        this.videoPlaying = false;
        if (this.videoCb) {
            this.videoCb(VIDEO_STATUS.ERR);
            this.videoCb = null!;
        }
    }

    public onVideoClose(isEnd: any) {
        Debug.log(MSG.VIDEO_CLOSE_COMPLETED, isEnd.isEnded)
        this.videoLoading = false;
        this.videoPlaying = false;
        eventUtil.sendEventImmediately(EventConst.ON_PLATFORM_SHOW, null);
        if (!!isEnd.isEnded) {
            httpUtil.clickVideo();
        }
        if (this.videoCb) {
            let ret = (!!isEnd.isEnded) ? VIDEO_STATUS.END : VIDEO_STATUS.NOTEND;
            setTimeout(() => {
                this.videoCb(ret);
            }, 50);
        }
    }

    public onVideoLoad() {
        Debug.log(MSG.VIDEO_LOAD_COMPLETED)
        this.videoLoading = false;
    }
    /**
     * 唤起视频
     * @param completeCallback 
     * @param position
     */
    public showVideo(completeCallback?: (res: any) => void, idIndex: number = 0) {
        Debug.log('显示video')
        this.videoCb = completeCallback;
        this.createRewardAD(true, idIndex);
    }

    //--------------插屏广告---------------
    private loadCompletedShow: boolean = false;
    public prepareInter() {
        if (!Guyu.RuntimeSDK.onWXMiniGame) {
            return;
        }
        let xx = ADController.m_插屏广告;
        return;

        if (!this.checkWindow()) return;
        var win = this.getWindow();
        if (!win[this.platformName].createInterstitialAd) return;

        if (Common.isEmpty(this.interId)) {
            Debug.warn(MSG.INTER_KEY_IS_NULL);
            return;
        }
        this.inter = win[this.platformName].createInterstitialAd({
            adUnitId: this.interId
        });
        this.inter.onLoad(this._onInterLoad.bind(this));
        this.inter.onClose(this._onInterClose.bind(this));
        this.inter.onError(this._onInterError.bind(this));
        this.inter.load();
    }
    public showInter() {
        this.loadCompletedShow = true;
        ADController.m_插屏广告.show();
        return;

        this.loadCompletedShow = true;
        if (!this.inter) {
            this.prepareInter();
        }
        else {
            this.inter.load();
        }
        if (this.isInterLoaded)
            this.inter.show();
    }
    public _onInterLoad() {
        this.isInterLoaded = true;
        if (this.loadCompletedShow) {
            this.inter.show();
        }
    }
    public _onInterClose() {
        this.loadCompletedShow = false;
    }
    public _onInterError(err: any) {
        Debug.log(`插屏广告出错：`, err)
    }


    public prepareNative(index: number = -1, isLoad: boolean = false) {
    }

    public _onNativeLoad(res: any) {
    }

    public _onNativeError(err: any) {
    }

    public destroyNative() {
    }

    /**
     * 目前只有OPPO平台有此功能
     * 返回原生广告数据，开发者根据返回的数据来展现
     * 没有广告返回null
     * 
     * 
     * 例如 cocos
     * let adData=platformUtil.currentPlatform.getNativeAd();
     * cc.loader.load(adData.imgUrlList[0], (err, texture) => {
     *   adImg.active = true
     *   adImg.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture)
     * })
     * 
     * 例如 laya
     * let adData=platformUtil.currentPlatform.getNativeAd();
     * new Laya.Image().skin=adData.imgUrlList[0];
     * 
     * @param callback 回调函数
     */
    public showNativeAd(callback: Function, remoteStatus: boolean = false) {
        if (Common.isFunction(callback))
            callback();
    }

    public showNativePicAd(options: NativeOptions, index: number = -1, onClose: () => void, onError: () => void) {

    }
    public hideNativePicAd() {

    }

    public showNativeLRAd(left = null, top = null, callback?: (Function)) {

    }
    public hideNativeLRAd() {

    }
    private lstCustomAd: { [index: number]: any } = {};
    private mCustomOptions: CustomOptions;
    public GetRandomGroup(ids: Array<CustomAdGroup>, index: number = -1): CustomAdGroup {
        if (ids.length > 0) {
            if (index == -1)
                return ids[Common.randomNumBoth(0, ids.length - 1)];
            else {
                if (index < ids.length) {
                    return ids[index];
                }
            }
        }
        return ids[0];
    }
    public GetCustomStyle(randomGroup: CustomAdGroup) {

        var horizontal = this.mCustomOptions.Horizontal;
        var vertical = this.mCustomOptions.Vertical;

        var wxsys = this.getSystemInfoSync();
        let visibleSize = View.instance.getVisibleSize()
        if (!wxsys) {
            wxsys = {
                windowWidth: visibleSize.width,
                windowHeight: visibleSize.height
            }
        }
        let windowWidth = wxsys.windowWidth;
        let windowHeight = wxsys.windowHeight;
        let top = 0;
        let left = 0;
        // 
        // Debugger.LogInfo("2-----显示banner horizontal {0}  vertical {1}", horizontal==AdHorizontal.CENTER, vertical==AdVertical.TOP);
        switch (vertical) {
            case AdVertical.TOP:
                top = 0;
                break;
            case AdVertical.CENTER:
                top = (windowHeight - this.mCustomOptions.Height) / 2;
                break;
            case AdVertical.BOTTOM:
                top = windowHeight - this.mCustomOptions.Height;
                break;
            case AdVertical.CUSTOM:
            default:
                top = this.mCustomOptions.Top;
                break;
        }
        switch (horizontal) {
            case AdHorizontal.LEFT:
                left = 0;
                break;
            case AdHorizontal.CENTER:
                left = (windowWidth - this.mCustomOptions.Width) / 2;
                break;
            case AdHorizontal.RIGHT:
                left = windowWidth - this.mCustomOptions.Width;
                break;
            case AdHorizontal.CUSTOM:
            default:
                left = this.mCustomOptions.Left;
                break;
        }
        var style =
        {
            left: (left + this.mCustomOptions.Offset.x),
            top: (top + this.mCustomOptions.Offset.y),
            isFixed: true,
            width: visibleSize.height > visibleSize.width ? (this.mCustomOptions.Width) : 330
        };
        return style;
    }


    public prepareCustom(options: CustomOptions, index: number, onClose: () => void, onError: () => void) {

        if (!this.checkWindow()) return;
        let win = this.getWindow();
        if (win[this.platformName] && !win[this.platformName].createCustomAd) return;

        this.mCustomOptions = options;
        let randomGroup = this.GetRandomGroup(platformConf.config.customIdList, index);
        this.mCustomOptions.currentSize = randomGroup.Size;
        let customStyle = this.GetCustomStyle(randomGroup);
        let style = {
            left: customStyle.left,
            top: customStyle.top,
            width: customStyle.width,
            fixed: true
        }
        Debug.log('prepareCustom style ', style);
        let zs_matrix_renovate = memoryConfig.instance.getIntKey("zs_matrix_renovate", 30);
        let m_gridAd = window[this.platformName].createCustomAd({
            adUnitId: randomGroup.Id,
            adIntervals: zs_matrix_renovate,
            style: style
        })
        m_gridAd.onClose(() => {
            // this.lstCustomAd[index] = null;
            if (onClose != null) {
                m_gridAd.destroy();
                onClose();
            }
        });
        m_gridAd.onError((response) => {
            delete this.lstCustomAd[index];
            if (onError != null) {
                m_gridAd.destroy();
                onError();
            }
        });
        this.lstCustomAd[index] = m_gridAd;
    }

    public showCustomAd(options: CustomOptions, index: number, onClose = null) {
        if (this.lstCustomAd.hasOwnProperty(index)) {
            this.lstCustomAd[index].show();
            Debug.log('showCustomAd style ', this.lstCustomAd[index].style);
        }
        else {
            this.prepareCustom(options, index, onClose, () => {

            });
            if (this.lstCustomAd.hasOwnProperty(index))
                this.lstCustomAd[index].show();
        }
    }
    public hideCustomAd(index?: number) {
        if (!isNaN(index) && this.lstCustomAd.hasOwnProperty(index)) {
            this.lstCustomAd[index].hide();
        }
        else {
            for (let k in this.lstCustomAd) {
                if (this.lstCustomAd.hasOwnProperty(k) && this.lstCustomAd[k] != null) {
                    this.lstCustomAd[k].hide();
                }
            }
        }
    }
    /**
     * 目前只有OPPO平台有此功能 
     * 用户点击了展示原生广告的图片时，使用此方法
     * 例如 cocos
     * this.node.on(cc.Node.EventConst.TOUCH_END, () => {
     *     platformUtil.currentPlatform.clickNative();
     * }, this)
     * 
     * 
     * 例如 laya
     * (new Laya.Image()).on(Laya.Event.MOUSE_UP, this, () => {
     *     platformUtil.currentPlatform.clickNative();
     * })
     * 
     */
    public clickNative(callback?: Function) {
    }



    /**
    * 盒子广告
    * @param callback 关闭回调
    * @param remoteOn 被后台开关控制
    */
    public showAppBox(callback?: Function, remoteOn: boolean = true) {
        if (Common.isFunction(callback))
            if (callback)
                callback();
    }

    /**
     * 
     * @param callback 
     */
    public hideAppBox(callback?: Function) {
        if (Common.isFunction(callback))
            if (callback)
                callback();
    }

    /**
     * 平台数据上报
     * @param name 
     * @param value 
     */
    public reportMonitor(name?: string, value?: string) {

    }

    /**
     * 更多游戏按钮
     * @param url 
     * @param callback 
     * @param style 
     */
    public showMoreGameButton(url: string, callback?: Function, style = null) {
        if (callback)
            callback();
    }




    //----自定义--
    public initRank() {
        let data = {
            action: 1,
        };
        this.postMessage(data);
    }
    public showRank() {
        let data = {
            action: 10,
        };
        this.postMessage(data);
    }
    public updateUserScore(score: number) {
        let data = {
            action: 13,
            data: score,
        };
        this.postMessage(data);
    }
    public hideRank() {
        let data = {
            action: 20,
        }
        this.postMessage(data);
    }

    /**
     * 用户是否关注抖音号
     * @param success 
     * @param fail 
     */
    public checkFollowAwemeSate(success: (hasFollowed: boolean) => void, fail: (err: any) => void) {
        if (success)
            success(true)
    }
    /**
     * 调用后跳转个人主页，并且回调关注成功/失败回调，异步回调接口
     * @param success 
     * @param fail 
     */
    public openAwemeUserProile(success: (hasFollowed: boolean) => void, fail: (err: any) => void) {
        if (success)
            success(true)
    }

    public hasShortcutInstalled(success: (has: boolean) => void, fail: (err: any) => void) {
        success(false)
    }

    public installShortcut(success: (res: any) => void, message: string = "方便下次快速启动", fail: (err: any) => void) {

    }
    public showBlock(option: BlockOptions, orientation: number = 1, size: number = 5) {

    }

    public hideBlock() {

    }
    private isLoaded: boolean = false;


    public gameBannerAd: any;
    public gamePortalAd: any;
    public showGameBannerAd() {

    }
    public hideGameBannerAd() {

    }

    public showGamePortalAd(onClose?: () => void, onShow?: (success: boolean) => void) {
        if (onShow)
            onShow(false);
        // if (onClose)
        //     onClose();
    }

    public hideGamePortalAd() {

    }

    public showBoxPortalAd(image: string, marginTop: number = 200, onClose?: () => void, onShow?: (success: boolean) => void) {
        if (onShow)
            onShow(false);
    }

    public hideBoxPortalAd() {

    }

    public nativeOnLoadCallback() { }


}